package com.fengye.cluster.impl;

import com.fengye.cluster.ClusterStrategy;
import com.fengye.model.ProviderService;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author fengye
 * @Date 2023/2/15 13:22
 **/
public abstract class AbstractClusterStrategt implements ClusterStrategy {
    @Override
    public ProviderService select(List<ProviderService> providerServiceList) {
        ProviderService providerService = doSelect(providerServiceList);
        if(providerService == null) {
            providerService = randomCluster(providerServiceList);
        }
        return providerService;
    }

    /**
     * 软负载算法
     *
     * @param providerServiceList
     * @return
     */
    protected abstract ProviderService doSelect(List<ProviderService> providerServiceList) ;

    /**
     * 随机加权算法
     *
     * @param providerServiceList
     * @return
     */
    protected ProviderService randomCluster(List<ProviderService> providerServiceList) {
        int maxLen = providerServiceList.size();
        int index = ThreadLocalRandom.current().nextInt(0, maxLen-1);
        return providerServiceList.get(index);
    }
}
